﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 文件上传/下载服务
    /// </summary>
    public class FileuploadService
    {
        /// <summary>
        /// 9101 文件上传
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<OutputFileUpload> Upload(FsiRequestHeader<InputFileupload> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            Random rnd = new Random();
            DateTime dateTime = DateTime.Now;
            long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
            string zipPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\file", $"{fsiRequest.fixmedins_code}-{dateTime.ToString("yyyyMMddHHmmssfff")}.zip");
            byte[] byteArray = Array.ConvertAll(fsiRequest.Input.fsUploadIn.@in, i => (byte)i);
            File.WriteAllBytes(zipPath, byteArray);
            // 将zip解压到指定目录，并自动覆盖重复文件
            string unzipPath = AppDomain.CurrentDomain.BaseDirectory + "\\file";
            using (var archive = new ZipArchive(new MemoryStream(byteArray), ZipArchiveMode.Read))
            {
                foreach (var entry in archive.Entries)
                {
                    string destPath = Path.Combine(unzipPath, entry.FullName);
                    Directory.CreateDirectory(Path.GetDirectoryName(destPath)); // 确保目标路径的目录存在
                    entry.ExtractToFile(destPath, true); // true 表示覆盖现有文件
                }
            }
            //解压后删除zip文件
            File.Delete(zipPath);
            var output = new OutputFileUpload
            {
                filename = fsiRequest.Input.fsUploadIn.filename,
                file_qury_no = unzipPath + "\\" + fsiRequest.Input.fsUploadIn.filename,
                dld_endtime = dateTime.AddDays(1).ToString("yyyyMMddHHmmssfff"),
            };
            return output;
        }
        /// <summary>
        /// 9102 文件下载
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<HttpResponseMessage> Download(FsiRequestHeader<InputFileDownload> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            Random rnd = new Random();
            DateTime dateTime = DateTime.Now;
            string filePath = fsiRequest.Input.fsDownloadIn.file_qury_no;
            //判断传入的文件是否存在
            if (!File.Exists(filePath))
            {
                throw new Exception("根据传入的文件路径查询不到文件！");
            }
            var fileBytes = System.IO.File.ReadAllBytes(filePath);
            var fileName = Path.GetFileName(filePath);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(fileBytes)
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            };
            //删除文件
            File.Delete(filePath);
            return result;
        }
    }
}
